<?php


namespace App\Http\Controllers\Web;

use App\Models\Order;
use App\Models\User;

/**
 * 用户
 * Class UserController
 * @package App\Http\Controllers\Web
 */
class UserController extends Controller
{
    /**
     * 查找用户
     */
    public function searchUser()
    {
        $query = $this->query;
        $callback = request()->input('callback');
        $escort_id = request()->input('escort_id');
        $is_leader = request()->input('is_leader');
        $builder = User::query();

        if($is_leader){
            $builder->whereIsLeader(1);
        }
        if($query['keywords']){
            $builder->where(function($q) use($query){
                $q->where('nickname', 'like', "%{$query['keywords']}%")
                    ->orWhere('mobile', $query['keywords']);
            });
        }
        $pager = $builder->paginate($this->pageNum);
        return view('user.user_list', [
            'pager' => $pager,
            'callback' => $callback,
            'escort_id' => $escort_id,
            'query' => $query
        ]);
    }

    /**
     * 会员列表
     */
    public function userList()
    {
        $id = request()->input('id');
        $nickname = request()->input('nickname');
        $phone = request()->input('phone');

        $builder = User::query();
        if($id){
            $builder->whereKey($id);
        }
        if($nickname){
            $builder->whereNickname($nickname);
        }
        if($phone){
            $builder->whereMobile($phone);
        }
        $builder->orderBy('id','desc');

        $users = $builder->paginate($this->pageNum);
        $users->map(function($item){

            $totalPay = Order::whereType(1)->whereUid($item->id)->where('status', '>=', 1)->sum('pay_price');
            $totalCount = Order::whereType(1)->whereUid($item->id)->where('status', '>=', 1)->count();
            $item->pay = $totalPay;
            $item->count = $totalCount;
        });
        return view('user.index', ['users' => $users]);
    }

    /**
     * 设置成为镖头
     */
    public function beLeader()
    {
        $id = request()->input('id');
        $user = User::find($id);

        $user->is_leader = 1;
        $user->save();

        if($user->escort){
            $user->escort->role = 2;
            $user->escort->save();
        }

        return $this->success();

    }

    /**
     * 设置成为镖头
     */
    public function cancelLeader()
    {
        $id = request()->input('id');
        $user = User::find($id);

        $user->is_leader = 0;
        $user->save();

        if($user->escort){
            $user->escort->role = 1;
            $user->escort->save();
        }

        return $this->success();
    }
}